import urllib2,simplejson,zlib,logging
LOG_FILENAME = "moth-py.log"

class API:
	def __init__(self,baseUrl):
		self.baseUrl = baseUrl
		logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
	
	def get(self,uri):
		logging.debug("GET: "+self.baseUrl+uri)
		opener = self.__getOpener()
		request = self.__getRequest("GET",self.baseUrl+uri,"")
		connection = opener.open(request)
		return self.__getJson(connection)

	def post(self,uri,putData):
		opener = self.__getOpener()
		logging.debug("POST: "+self.baseUrl+uri+" with data: "+putData)
		request = self.__getRequest("POST",self.baseUrl+uri,putData)
		connection = opener.open(request)
		return self.__getJson(connection) 
	
	def put(self,uri,putData):
		opener = self.__getOpener()
		logging.debug("PUT: "+self.baseUrl+uri+" with data: "+putData)
		request = self.__getRequest("PUT",self.baseUrl+uri,putData)
		connection = opener.open(request)
		return self.__getJson(connection)

	def delete(self,uri,delData):
		opener = self.__getOpener()
		logging.debug("DELETE: "+self.baseUrl+uri+" with data: "+delData)
		request = self.__getRequest("DELETE",self.baseUrl+uri,delData)
		connection = opener.open(request)
		return self.__getJson(connection)

	def __getJson(self,connection):
		requestData = connection.read()
		headers = connection.info()
		if headers.get("Content-Encoding") == "gzip":
			requestData = zlib.decompress(requestData,16+zlib.MAX_WBITS)
		return simplejson.loads(requestData)

	def __getOpener(self):
		return urllib2.build_opener(urllib2.HTTPHandler)
	
	def __getRequest(self,requestType,url,requestData):
		request = urllib2.Request(url,data=requestData)
		request.add_header('Content-Type','application/json')
		request.get_method = lambda:requestType
		return request

